package filter;

import bean.User;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1.实现对用户访问主页面的过滤操作
        //因为LoginServlet中的setAttribute是用的HttpServlet中的request方法
        //而HttpServlet是ServletRequest的子类 不能直接获取session对象，所以在这里需要进行强转
        HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest;
        //2.如果session中是否有用户名信息，放行
        HttpSession session = httpServletRequest.getSession();
        User user = (User) session.getAttribute("user");
        //获取Servlet的请求路径
        String servletPath = httpServletRequest.getServletPath();
        String username = null;
        if (null != user && servletPath.contains("adminLoginServlet")){
            filterChain.doFilter(servletRequest, servletResponse);
        }else {
            //弱国没有登陆，就去查询Cookie信息中是否有用户名登陆过的信息
            Cookie[] cookies = httpServletRequest.getCookies();
            if (cookies != null && cookies.length > 0){
                for (Cookie cookie : cookies) {
                    String name = cookie.getName();
                    if ("username".equals(name)){
                        username = name;
                        break;
                    }
                }
            }
        }
        if (null != username){
            filterChain.doFilter(servletRequest, servletResponse);
        }else {
            RequestDispatcher requestDispatcher = servletRequest.getRequestDispatcher("login.jsp");
            requestDispatcher.forward(servletRequest, servletResponse);

        }
    }

    @Override
    public void destroy() {

    }
}
